package com.lagou.edu.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    private boolean doAuth(HttpServletRequest request){
        //在session中获取登录信息
        Boolean isAuth = (Boolean) request.getSession().getAttribute("isAuth");
        if (isAuth != null && isAuth){
            return true;
        }
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        if (userName == null || password == null){
            return false;
        }
        if (userName == "admin" && password == "admin"){
            return true;
        }
        return false;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在这里完成用户鉴权
        boolean isAuth = doAuth(request);
        //鉴权失败则返回登录界面
        if (!isAuth){
            response.sendRedirect("/login");
        }
        return isAuth;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==========postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("==========afterCompletion");
    }
}
